function [hsi] = rgb2hsi(rgb)

rgb = double(rgb);

[m n ~] = size(rgb);
R = rgb(:,:,1);
G = rgb(:,:,2);
B = rgb(:,:,3);

I = max(rgb,[],3);
minimum = min(rgb,[],3);

S = zeros([m n]);
S(I >= 0) = (I-minimum)./I;

difference = I - minimum;

h1 = (pi/3)*(G-B)./difference;
h2 = (2*pi/3) + (pi/3)*(B-R)./difference;
h3 = (4*pi/3) + (pi/3)*(R-G)./difference;

H = zeros([m n]);
H(B == I) = h3(B == I);
H(G == I) = h2(G == I);
H(R == I) = h1(R == I);

H(H <= 0) = H(H <= 0) + 2*pi;
H(S <= 0) = -1;

hsi = zeros(size(rgb));
hsi(:,:,1) = H;
hsi(:,:,2) = S;
hsi(:,:,3) = I;

end